package dameng

import (
	"context"
	"github.com/gogf/gf/v2/database/gdb"
)

const (
	tableFieldsSqlTpl = `
SELECT a.COLUMN_NAME,
	a.DATA_TYPE,
	b.COMMENTS,
	a.DATA_LENGTH,
	a.DATA_PRECISION,
	a.DATA_SCALE,
	a.DATA_DEFAULT,
	a.NULLABLE,
	CASE WHEN c.CONSTRAINT_NAME IS NOT NULL THEN 'PRI' ELSE '' END "KEY"
FROM ALL_TAB_COLUMNS a
	INNER JOIN ALL_COL_COMMENTS b ON b.COLUMN_NAME = a.COLUMN_NAME and b.TABLE_NAME = a.TABLE_NAME AND b.SCHEMA_NAME = a.OWNER
	LEFT JOIN ALL_CONS_COLUMNS c ON c.COLUMN_NAME = a.COLUMN_NAME and c.TABLE_NAME = a.TABLE_NAME AND c.OWNER = a.OWNER
WHERE a.TABLE_NAME = ?
ORDER BY a.COLUMN_ID
`
)

func (d *Driver) TableFields(ctx context.Context, table string, schema ...string) (fields map[string]*gdb.TableField, err error) {
	var (
		result gdb.Result
		link   gdb.Link
	)

	if link, err = d.MasterLink(); err != nil {
		return nil, err
	}
	sql, _ := gdb.FormatMultiLineSqlToSingle(tableFieldsSqlTpl)
	result, err = d.DoSelect(ctx, link, sql, table)

	if err != nil {
		return nil, err
	}
	fields = make(map[string]*gdb.TableField)
	for i, m := range result {
		fields[m["COLUMN_NAME"].String()] = &gdb.TableField{
			Index:   i,
			Name:    m["COLUMN_NAME"].String(),
			Type:    m["DATA_TYPE"].String(),
			Null:    m["NULLABLE"].String() == "Y",
			Default: m["DATA_DEFAULT"].Val(),
			Key:     m["KEY"].String(),
			Comment: m["COMMENTS"].String(),
		}
	}

	return fields, nil
}
